﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace WholeSlideImageLibrary.Formats
{
    internal class FileSourceReaderCache : IAsyncDisposable
    {
        private FileSourceInfo? _fileInfo;
        private FileSourceReader? _cache;

        public FileSourceReaderCache(FileSourceInfo fileInfo)
        {
            _fileInfo = fileInfo;
        }

        public ValueTask<FileSourceReader> RentAsync(CancellationToken cancellationToken)
        {
            FileSourceInfo? fileInfo = _fileInfo;
            if (fileInfo is null)
            {
                throw new ObjectDisposedException(nameof(FileSourceReaderCache));
            }

            FileSourceReader? cache = Interlocked.Exchange(ref _cache, null);
            return cache is null ? fileInfo.OpenAsync(cancellationToken) : new ValueTask<FileSourceReader>(cache);
        }

        public ValueTask ReturnAsync(FileSourceReader reader)
        {
            if (reader is null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            if (_fileInfo is null)
            {
                return reader.DisposeAsync();
            }

            FileSourceReader? oldReader = Interlocked.Exchange(ref _cache, reader);
            if (!(oldReader is null))
            {
                return oldReader.DisposeAsync();
            }

            return default;
        }

        public ValueTask DisposeAsync()
        {
            _fileInfo = null;
            FileSourceReader? cache = Interlocked.Exchange(ref _cache, null);
            if (!(cache is null))
            {
                return cache.DisposeAsync();
            }
            return default;
        }

    }
}
